package com.jerry.hm.datastructure.stack;

import java.util.Iterator;

/**
 * 链表实现的栈
 *
 * @author Jerry
 * @since 2024/10/3 17:13
 */
public class LinkedListStack<E> implements Stack<E>, Iterable<E> {

    static class Node<E> {

        /**
         * 下一个节点
         */
        Node<E> next;

        /**
         * 节点值
         */
        E value;

        public Node(Node next, E value) {
            this.next = next;
            this.value = value;
        }
    }

    private int capacity;
    private int size;
    private Node<E> head = new Node<>(null, null);

    public LinkedListStack(int capacity) {
        this.capacity = capacity;
    }

    /**
     * 向栈顶压入元素
     *
     * @param e
     * @return
     */
    @Override
    public boolean push(E e) {
        if (isFull()) {
            return false;
        }
        head.next = new Node<>(head.next, e);
        size++;
        return true;
    }

    /**
     * 从栈顶弹出元素
     *
     * @return
     */
    @Override
    public E pop() {
        if (isEmpty()) {
            return null;
        }
        Node<E> target = head.next;
        head.next = target.next;
        size--;
        return target.value;
    }

    /**
     * 获取栈顶的元素
     *
     * @return
     */
    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return head.next.value;
    }

    /**
     * 栈是否为空
     *
     * @return
     */
    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 栈是否满
     *
     * @return
     */
    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {

        return new Iterator<>() {

            private Node<E> cur = head.next;

            @Override
            public boolean hasNext() {
                return cur != null;
            }

            @Override
            public E next() {
                Node<E> target = cur;
                cur = cur.next;
                return target.value;
            }
        };
    }
}
